﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using BlizzardApi.Services;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Tar;
using Model;
using Utility;

namespace Command.Commands
{
    public class SyncItemsCommand : BaseCommand<Options>
    {
        private readonly IRepository _repository;
        private readonly IResponseParser _responseParser;

        public SyncItemsCommand(IRepository repository, IResponseParser responseParser)
        {
            _repository = repository;
            _responseParser = responseParser;
        }

        protected override void InternalExecute(Options options)
        {
            IEnumerable<string> itemResponses = LoadItemData();
            foreach (var itemResponse in itemResponses)
            {
                var itemRecord = _responseParser.Parse<BlizzardApi.Model.Item>(itemResponse);
                var item = _repository.Query<Item>().FirstOrDefault(x => x.ExternalKey == itemRecord.ID);
                if (item == null)
                {
                    item = new Item
                        {
                            ExternalKey = itemRecord.ID,
                            Description = itemRecord.Description,
                            Level = itemRecord.ItemLevel,
                            Name = itemRecord.Name,
                            RequiredLevel = itemRecord.RequiredLevel
                        };
                    Console.WriteLine("Creating missing item: {0}", item.Name);
                    _repository.Save(item);
                }
            }
        }

        private static IEnumerable<string> LoadItemData()
        {
            var itemData = new List<string>();
            using (var fs = File.OpenRead("Static\\Data\\itemdata_4.3.tar.gz"))
            {
                using (var gzip = new GZipInputStream(fs))
                {
                    using (var tar = new TarInputStream(gzip))
                    {
                        TarEntry tarEntry;

                        while ((tarEntry = tar.GetNextEntry()) != null)
                        {
                            if (tarEntry.IsDirectory)
                                continue;
                            using (var ms = new MemoryStream())
                            {
                                tar.CopyEntryContents(ms);
                                ms.Rewind();
                                var buffer = ms.GetBuffer();
                                var item = Encoding.UTF8.GetString(buffer);
                                itemData.Add(item);
                            }
                        }
                    }
                }
            }
            return itemData;
        }
    }
}
